using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Controls;
using TXLooker.Common;
using Microsoft.Win32;
using TXLooker.WorkItemExtention.Properties;


namespace TXLooker.WorkItemExtention.UI.OLViewExtension
{
    public partial class OLQueryViewControl : UserControl
    {
        public WorkItemResultGrid QueryResultGrid;
        public WorkItemStore store;
        public StoredQuery storedQuery;
        private string queryID;
        private string columnsWidths;

        public OLQueryViewControl(WorkItemStore Store, StoredQuery StoredQuery)
        {
            InitializeComponent();
            Application.EnableVisualStyles();

            store = Store;
            storedQuery = StoredQuery;
            var QueryText = storedQuery.QueryText.Replace("@project", string.Format("'{0}'", storedQuery.Project.Name));
            QueryResultGrid = new WorkItemResultGrid
                                  {
                                      Size = new Size(Size.Width - 10, Size.Height - 5),
                                      StandardTab = true,
                                      PauseBeforeFill = 10,
                                      ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Raised,
                                      AllowUserToOrderColumns = true,
                                      Font = new Font("Segoe UI", 8.25F, FontStyle.Regular, GraphicsUnit.Point, 204),
                                      CellBorderStyle = DataGridViewCellBorderStyle.SingleHorizontal,
                                      SortBackcolor = Color.FromArgb(245, 245, 245),
                                      MultiSelect = false,
                                      StretchLastColumn = true
                                  };

            QueryResultGrid.LoadFromWiql(store, QueryText);
            queryID = storedQuery.QueryGuid.ToString();
            try
            {
                if (IsQueryInRegistry())
                {
                    LoadWidthsFromRegistry();
                }
                else
                {
                    SaveColumnWidthsToRegistry();
                }
            }
            catch (Exception ex)
            {

                LogManager.WriteMessageToCustomLog(ex);
            }



            Controls.Add(QueryResultGrid);
            QueryResultGrid.ColumnHeaderMouseClick += OnQueryResultGrid_ColumnHeaderMouseClick;
            QueryResultGrid.ColumnWidthChanged += OnQueryResultGrid_ColumnWidthChanged;
        }

        private void OnQueryResultGrid_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
        {
            SaveColumnWidthsToRegistry();
        }

        private void LoadWidthsFromRegistry()
        {
            try
            {
                columnsWidths = GetColumnsWidthsFromRegistry();
                QueryResultGrid.ResultOptions.LoadColumnWidthsFromString(columnsWidths);
                QueryResultGrid.RefreshGrid(true, true, true);
            }
            catch (Exception ex)
            {
                LogManager.WriteMessageToCustomLog(ex);
            }
        }

        private String GetColumnsWidthsFromRegistry()
        {
            var key = Resources.REGISTRY_FULL_PATH;
            return Registry.GetValue(key, queryID, String.Empty).ToString();
        }

        private void SaveColumnWidthsToRegistry()
        {
            QueryResultGrid.Refresh();
            columnsWidths = QueryResultGrid.ResultOptions.ColumnWidthsToString();
            var key = Resources.REGISTRY_FULL_PATH;
            Registry.SetValue(key, queryID, columnsWidths, RegistryValueKind.String);
        }

        private bool IsQueryInRegistry()
        {
            var curUser = Registry.CurrentUser;
            var lookersKey = curUser.OpenSubKey(Resources.REGISTRY_RELATIVE_PATH);
            var listID = new List<String>(lookersKey.GetValueNames());
            return listID.Contains(queryID);
        }

        private void OnQueryResultGrid_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            var fieldName = QueryResultGrid.Columns[e.ColumnIndex].Name;
            var sortFields = QueryResultGrid.ResultOptions.SortFields;
            var workItemCollection = QueryResultGrid.WorkItemCollection;
            var ascending = SortType.Ascending;
            // additional check
            var sortField = new Microsoft.TeamFoundation.WorkItemTracking.Client.SortField(store, fieldName, ascending);
            if (!sortField.FieldDefinition.CanSortBy)
                return;

            if (sortFields.Contains(fieldName))
                ascending = sortFields[fieldName].Ascending ? SortType.Descending : SortType.Ascending;

            sortFields.Clear();
            workItemCollection.SortFields.Clear();

            sortFields.Add(new Microsoft.TeamFoundation.WorkItemTracking.Controls.SortField(fieldName, ascending == SortType.Ascending));
            workItemCollection.SortFields.Add(fieldName, ascending);

            QueryResultGrid.ResultOptions = new ResultOptions(QueryResultGrid.ResultOptions.DisplayFields, sortFields);
            workItemCollection.Resort();
            QueryResultGrid.WorkItemCollection = workItemCollection;
            try
            {
                QueryResultGrid.RefreshGrid(true, true, true);
            }
            catch (Exception ex)
            {
                LogManager.WriteMessageToCustomLog(ex);
            }
        }

        protected void OnMyPanel_SizeChanged(object sender, EventArgs e)
        {
            QueryResultGrid.Size = new Size(Size.Width - 10, Size.Height - 5);
        }

        private void DockedControl_Load(object sender, EventArgs e)
        {
            //this.BackColor = Color.White;
        }

    }
}